package com.flame.core.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public final class DateUtils {

    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static final String YYYY_MM_DD = "yyyy-MM-dd";

    private DateUtils() {
    }

    public static String currentDateTime() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    public static String currentDate() {
        return LocalDate.now().format(DateTimeFormatter.ofPattern(YYYY_MM_DD));
    }

    public static Date parse(String dateStr, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new Date();
    }

    public static String diff(Date beginDate, Date endDate) {
        if (beginDate.compareTo(endDate) >= 0) {
            return "0";
        }
        long diff = endDate.getTime() - beginDate.getTime();
        long minute = diff / 1000 / 60;
        long second = diff / 1000 % 60;
        return String.format("%d分%d秒", minute, second);
    }

    public static long diff(long beginTimestamp, long endTimestamp, TimeUnit timeUnit) {
        if (TimeUnit.MILLISECONDS == timeUnit) {
            return endTimestamp - beginTimestamp;
        } else if (TimeUnit.SECONDS == timeUnit) {
            return endTimestamp / 1000 - beginTimestamp / 1000;
        } else if (TimeUnit.MINUTES == timeUnit) {
            return endTimestamp / 1000 / 60 - beginTimestamp / 1000 / 60;
        } else if (TimeUnit.HOURS == timeUnit) {
            return endTimestamp / 1000 / 60 / 60 - beginTimestamp / 1000 / 60 / 60;
        } else if (TimeUnit.DAYS == timeUnit) {
            return endTimestamp / 1000 / 60 / 60 / 24 - beginTimestamp / 1000 / 60 / 60 / 24;
        } else {
            return 0;
        }
    }

    public static String formatedDateTime(long timestamp) {
        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        return format.format(timestamp);
    }
}
